import { WebSocketServer } from "ws";
import Mock from "mockjs";

// 启动服务
const wss = new WebSocketServer({ port: 8081 });

Mock.Random.id();
Mock.Random.date();
Mock.Random.city();

// 监听客户端连接事件
wss.on("connection", (socket) => {
  // 每隔一段时间给客户端推送消息
  const timeId = setInterval(() => {
    const result = Mock.mock({
      "data|1-10": [
        {
          id: "@id",
          date: "@date",
          address: "@city",
          "num|1-10000": 1,
        },
      ],
    });

    socket.send(JSON.stringify(result.data));
  }, 1000);
  // 当客户端断开连接，清除定时器
  socket.once("close", () => {
    clearInterval(timeId);
  });

  // 心跳检测: 服务器接受客户端的消息，判断消息内容是否是ping, 如果是返回pong
  socket.on("message", (data) => {
    data = data.toString();
    if (data === "ping") {
      socket.send("pong");
    }
  });
});
